package com.xy.job.admin.repository

import com.xy.job.admin.domain.JobLock
import jakarta.persistence.LockModeType
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Lock
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query

interface JobLockRepository : JpaRepository<JobLock, Long> {

    @Lock(value = LockModeType.PESSIMISTIC_WRITE)
    @Query("select j.lockName from com.xy.job.admin.domain.JobLock j where lockName = :lockName")
    fun lock(lockName: String): String

    @Query("""
        select 
            j.lockName
        from 
            com.xy.job.admin.domain.JobLock j
        where owner = :owner
    """)
    fun findLockNameByOwner(owner: String): Iterable<String>

    @Query(
        """
        select 
            j.lockName
        from 
            com.xy.job.admin.domain.JobLock j
        where lockName in :lockNames
          and owner is null
    """
    )
    fun findLockNameWithoutOwner(lockNames: Iterable<String>): List<String>

    @Modifying
    @Query(
        """
        update 
            com.xy.job.admin.domain.JobLock j
        set owner = null
        where owner in :owners
    """
    )
    fun resetLockByOwner(owners: List<String>): Int
}